package com.xz.knowledgeDuplication.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间处理工具
 *
 * @author 召
 * @date 2021-12-26 21:02:08
 */
public class DateUtil {

    private final static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    private final static DateFormat dfhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 将字符串转换为日期格式
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static Date strToUtilDate(String str) throws Exception {
        return df.parse(str);
    }

    /**
     * 将字符串转换为日期格式
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static Date strToUtilDateHMS(String str) throws Exception {
        return dfhms.parse(str);
    }

    /**
     * 将日期格式转换为字符串
     *
     * @param date
     * @return
     */
    public static String utilDateToStr(Date date) {
        return df.format(date);
    }

    /**
     * 将日期格式转换为字符串
     *
     * @param date
     * @return
     */
    public static String utilDateToStrHMS(Date date) {
        return dfhms.format(date);
    }

    /**
     * 获取当前时间距离结束时间的秒数
     * 如果当前时间比结束时间晚则默认加上24小时
     *
     * @param hour
     * @param minute
     * @param second
     * @return
     */
    public static long getExpirationTTL(int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        long nowTime = calendar.getTimeInMillis();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        long endTime = calendar.getTimeInMillis();
        long ttl = (endTime - nowTime) / 1000;
        // 当前时间比结束时间晚则默认加上24小时
        if (ttl < 0) {
            ttl += 24 * 60 * 60;
        }
        return ttl;
    }

    /**
     * 获取今日开始时间
     *
     * @return
     */
    public static Date getCurrentStartDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取今日结束时间
     *
     * @return
     */
    public static Date getCurrentEndDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
}
